package cn.virens.web.components.websocket;

import java.io.IOException;
import java.security.Principal;

import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import com.alibaba.fastjson.JSON;

import cn.virens.exception.APIException;

public class WebSocketUtil {
	protected static int sendMessage(WebSocketSession session, JSON json) {
		return sendMessage(session, json.toJSONString());
	}

	protected static int sendMessage(WebSocketSession session, CharSequence text) {
		return sendMessage(session, new TextMessage(text));
	}

	protected static int sendMessage(WebSocketSession session, WebSocketMessage<?> message) {
		if (session == null) { return 0; }
		if (message == null) { return 0; }

		try {
			if (session.isOpen()) {
				session.sendMessage(message);

				return 1;
			} else {
				throw new APIException("colse", "连接已关闭");
			}
		} catch (IOException e) {
			throw new APIException("error", "发送失败", e);
		}
	}

	protected static SimplePrincipal getPrincipal(WebSocketSession session) {
		Principal p = session.getPrincipal();

		if (p instanceof SimplePrincipal) {
			return ((SimplePrincipal) p);
		} else {
			throw new APIException("noLogin", "未登录");
		}
	}

	protected static String getAccount(WebSocketSession session) {
		return getPrincipal(session).getAccount();
	}

	protected static String getName(WebSocketSession session) {
		return getPrincipal(session).getName();
	}

	protected static String getAvatar(WebSocketSession session) {
		return getPrincipal(session).getAvatar();
	}
}
